<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SpringBoot Excel 操作演示</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            color: white;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 25px;
            margin-bottom: 30px;
        }

        .section {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .section:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 40px rgba(0,0,0,0.15);
        }

        .section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.4rem;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-weight: 500;
        }

        select, input, textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s ease;
            background: #f8f9fa;
        }

        select:focus, input:focus, textarea:focus {
            outline: none;
            border-color: #667eea;
            background: white;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            margin: 5px;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            white-space: nowrap;
            vertical-align: middle;
            line-height: 1;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
        }

        .btn-success {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }

        .btn-warning {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
        }

        .btn-danger {
            background: linear-gradient(135deg, #dc3545 0%, #e83e8c 100%);
        }

        .result {
            margin-top: 15px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #667eea;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            max-height: 200px;
            overflow-y: auto;
            white-space: pre-wrap;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .downloads-section {
            grid-column: 1 / -1;
            background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
        }

        .downloads-form {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-success { background: #d4edda; color: #155724; }
        .status-error { background: #f8d7da; color: #721c24; }
        .status-warning { background: #fff3cd; color: #856404; }

        /* 导航栏样式 */
        .navbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            padding: 15px 30px;
            border-radius: 15px;
            margin-bottom: 20px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }

        .nav-brand {
            font-size: 1.2rem;
            font-weight: 600;
            color: #333;
        }

        .nav-links {
            display: flex;
            gap: 20px;
        }

        .nav-link {
            text-decoration: none;
            color: #666;
            padding: 8px 16px;
            border-radius: 8px;
            transition: all 0.3s ease;
            font-weight: 500;
        }

        .nav-link:hover {
            background: #667eea;
            color: white;
            transform: translateY(-2px);
        }

        .nav-link.active {
            background: #667eea;
            color: white;
        }

        @media (max-width: 768px) {
            .grid { grid-template-columns: 1fr; }
            .header h1 { font-size: 2rem; }
            .downloads-form { grid-template-columns: 1fr; }

            .navbar {
                flex-direction: column;
                gap: 15px;
                padding: 20px;
            }

            .nav-links {
                flex-wrap: wrap;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 导航栏 -->
        <nav class="navbar">
            <div class="nav-brand">SpringBoot Excel Demo</div>
            <div class="nav-links">
                <a href="/" class="nav-link active">主页面</a>
                <a href="/test_downloads.html" class="nav-link">异步导出测试</a>
                <a href="/test_image.html" class="nav-link">图片压缩测试</a>
                <a href="/test_easyexcel_import.html" class="nav-link">EasyExcel图片导入测试</a>
            </div>
        </nav>

        <div class="header">
            <h1>SpringBoot Excel 操作演示</h1>
            <p>支持 EasyExcel、EasyPoi、Hutool 三种Excel库的完整功能演示</p>
        </div>

        <div class="grid">
            <!-- 异步导出下载 -->
            <div class="section downloads-section">
                <h2>📊 异步导出下载</h2>
                <div class="downloads-form">
                    <div class="form-group">
                        <label for="downloadId">序号</label>
                        <input type="text" id="downloadId" placeholder="请输入序号">
                    </div>
                    <div class="form-group">
                        <label for="downloadName">姓名</label>
                        <input type="text" id="downloadName" placeholder="请输入姓名">
                    </div>
                    <div class="form-group">
                        <label for="downloadAge">年龄</label>
                        <input type="number" id="downloadAge" placeholder="请输入年龄">
                    </div>
                    <div class="form-group">
                        <label for="downloadGender">性别</label>
                        <select id="downloadGender">
                            <option value="">请选择性别</option>
                            <option value="1">男</option>
                            <option value="2">女</option>
                        </select>
                    </div>
                </div>
                <button class="btn btn-success" onclick="createDownloadTask()">创建导出任务</button>
                <button class="btn btn-secondary" onclick="getTaskList()">获取任务列表</button>
                <button class="btn btn-warning" onclick="window.open('/test_downloads.html', '_blank')">打开异步导出测试页面</button>
                <div id="downloadsResult" class="result"></div>
            </div>

            <!-- Excel 操作 -->
            <div class="section">
                <h2>📁 Excel 操作</h2>
                <div class="form-group">
                    <label for="excelType">Excel库类型</label>
                    <select id="excelType">
                        <option value="easyexcel">EasyExcel 🚀 (推荐，高性能)</option>
                        <option value="easypoi">EasyPoi 🛠️ (功能丰富)</option>
                        <option value="hutool">Hutool ✨ (简单易用)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="excelFile">选择文件</label>
                    <input type="file" id="excelFile" accept=".xlsx,.xls">
                </div>
                
                <!-- 基本操作按钮 -->
                <div style="margin-bottom: 15px;">
                    <button class="btn" onclick="uploadExcel()">📄 上传 Excel</button>
                    <button class="btn" onclick="downloadExcel()">📎 下载 Excel</button>
                    <button class="btn" onclick="downloadTemplate()">📝 下载模板</button>
                </div>
                
                <!-- 高级操作按钮 -->
                <div style="margin-bottom: 15px;">
                    <button class="btn btn-warning" onclick="processExcelAsync()">⏱️ 异步处理</button>
                    <button class="btn btn-success" onclick="exportExcel()">🚀 异步导出</button>
                </div>
                
                <!-- 快速测试区域 -->
                <div style="padding: 15px; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); border-radius: 10px; margin-bottom: 15px;">
                    <h4 style="color: #495057; margin: 0 0 10px 0; font-size: 14px;">🏃‍♂️ 快速测试</h4>
                    <button class="btn btn-success" onclick="quickExportTest()" style="margin-right: 10px; font-size: 13px; padding: 8px 16px;">
                        ⚡ 一键测试导出
                    </button>
                    <span style="color: #6c757d; font-size: 12px;">
                        快速创建一个测试导出任务，无需上传文件
                    </span>
                </div>
                
                <!-- 状态显示区域 -->
                <div id="excelResult" class="result"></div>
            </div>

            <!-- EnhancedExcelExporter 合并单元格测试 -->
            <div class="section">
                <h2>🔗 EnhancedExcelExporter 合并单元格测试</h2>
                <p style="color: #666; margin-bottom: 15px; font-size: 14px;">
                    测试EnhancedExcelExporter的合并单元格导出功能，包含退货包裹和货品的主从表结构
                </p>
                <button class="btn btn-success" onclick="testEnhancedExcelExport()">测试合并单元格导出</button>
                <div class="loading" id="enhancedLoading">
                    <div class="spinner"></div>
                    <p>正在生成Excel文件，请稍候...</p>
                </div>
                <div id="enhancedResult" class="result"></div>
            </div>

            <!-- 任务管理 -->
            <div class="section">
                <h2>⚙️ 任务管理</h2>
                <div class="form-group">
                    <label for="account">账户</label>
                    <input type="text" id="account" value="test" placeholder="账户">
                </div>
                <button class="btn" onclick="getTaskList()">获取任务列表</button>
                <button class="btn" onclick="getTaskStatus()">查询任务状态</button>
                <div class="form-group">
                    <label for="taskId">任务ID</label>
                    <input type="text" id="taskId" placeholder="任务ID">
                </div>
                <button class="btn btn-danger" onclick="cancelTask()">取消任务</button>
                <div id="taskResult" class="result"></div>
            </div>

            <!-- 枚举转换 -->
            <div class="section">
                <h2>🔄 枚举转换</h2>
                <div class="form-group">
                    <label for="genderCode">性别编码</label>
                    <input type="number" id="genderCode" value="1" placeholder="性别编码">
                </div>
                <button class="btn" onclick="convertGender()">编码转换测试</button>
                <div id="enumResult" class="result"></div>
            </div>

            <!-- 图片处理 -->
            <div class="section">
                <h2>🖼️ 图片处理</h2>
                <div class="form-group">
                    <label for="imageFile">选择图片</label>
                    <input type="file" id="imageFile" accept="image/*">
                </div>
                <button class="btn" onclick="compressImage()">压缩图片</button>
                <button class="btn btn-secondary" onclick="window.open('/test_image.html', '_blank')">打开图片压缩测试页面</button>
                <div id="imageResult" class="result"></div>
            </div>

            <!-- EasyExcel图片导入测试 -->
            <div class="section">
                <h2>📋 EasyExcel图片导入测试</h2>
                <p style="color: #666; margin-bottom: 15px; font-size: 14px;">
                    使用EasyExcel结合自定义监听器实现Excel数据读取和图片提取功能
                </p>
                
                <div class="form-group">
                    <label for="easyExcelFile">选择Excel文件</label>
                    <input type="file" id="easyExcelFile" accept=".xlsx,.xls" onchange="handleEasyExcelFileSelect(this)">
                </div>
                
                <div id="easyExcelFileInfo" style="display: none; margin-bottom: 15px; padding: 10px; background: #f8f9fa; border-radius: 6px; border-left: 4px solid #28a745;">
                    <strong>已选择文件：</strong>
                    <span id="easyExcelFileName"></span>
                    <br>
                    <strong>文件大小：</strong>
                    <span id="easyExcelFileSize"></span>
                </div>

                <div style="margin-bottom: 15px;">
                    <button class="btn btn-success" onclick="downloadEasyExcelTemplate()">📅 下载测试模板</button>
                    <button class="btn btn-warning" onclick="importEasyExcelData()">📊 导入Excel数据</button>
                    <button class="btn btn-secondary" onclick="window.open('/test_easyexcel_import.html', '_blank')">打开完整测试页面</button>
                </div>

                <div class="loading" id="easyExcelLoading" style="display: none;">
                    <div class="spinner"></div>
                    <p>正在处理Excel文件，请稍候...</p>
                </div>

                <div id="easyExcelResult" class="result" style="display: none;"></div>
                
                <!-- 统计信息卡片 -->
                <div id="easyExcelStats" style="display: none; margin-top: 20px;">
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 15px;">
                        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; text-align: center; border-left: 4px solid #667eea;">
                            <div id="easyExcelDataCount" style="font-size: 24px; font-weight: bold; color: #667eea;">0</div>
                            <div style="font-size: 12px; color: #666; margin-top: 5px;">数据行数</div>
                        </div>
                        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; text-align: center; border-left: 4px solid #28a745;">
                            <div id="easyExcelImageCount" style="font-size: 24px; font-weight: bold; color: #28a745;">0</div>
                            <div style="font-size: 12px; color: #666; margin-top: 5px;">图片数量</div>
                        </div>
                        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; text-align: center; border-left: 4px solid #ffc107;">
                            <div id="easyExcelProcessTime" style="font-size: 24px; font-weight: bold; color: #ffc107;">0s</div>
                            <div style="font-size: 12px; color: #666; margin-top: 5px;">处理时间</div>
                        </div>
                    </div>
                </div>

                <!-- 数据预览表格 -->
                <div id="easyExcelDataPreview" style="display: none; margin-top: 20px;">
                    <h3 style="color: #333; margin-bottom: 15px; font-size: 1.1rem;">📋 导入的数据预览</h3>
                    <div style="max-height: 300px; overflow-y: auto; border: 1px solid #e1e5e9; border-radius: 8px;">
                        <table id="easyExcelDataTable" style="width: 100%; border-collapse: collapse;">
                            <thead>
                                <tr style="background-color: #667eea; color: white;">
                                    <th style="border: 1px solid #ddd; padding: 8px; text-align: left;">行号</th>
                                    <th style="border: 1px solid #ddd; padding: 8px; text-align: left;">姓名</th>
                                    <th style="border: 1px solid #ddd; padding: 8px; text-align: left;">年龄</th>
                                    <th style="border: 1px solid #ddd; padding: 8px; text-align: left;">图片1</th>
                                    <th style="border: 1px solid #ddd; padding: 8px; text-align: left;">图片2</th>
                                    <th style="border: 1px solid #ddd; padding: 8px; text-align: left;">备注</th>
                                </tr>
                            </thead>
                            <tbody id="easyExcelDataTableBody">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 创建导出任务
        async function createDownloadTask() {
            const id = document.getElementById('downloadId').value;
            const name = document.getElementById('downloadName').value;
            const age = document.getElementById('downloadAge').value;
            const gender = document.getElementById('downloadGender').value;

            const downloadData = {
                id: id || null,
                name: name || null,
                age: age ? parseInt(age) : null,
                gender: gender ? parseInt(gender) : null
            };

            try {
                const response = await fetch('/api/excel/downloads', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(downloadData)
                });
                const result = await response.json();
                document.getElementById('downloadsResult').textContent = JSON.stringify(result, null, 2);
            } catch (error) {
                document.getElementById('downloadsResult').textContent = '错误: ' + error.message;
            }
        }

        async function uploadExcel() {
            const file = document.getElementById('excelFile').files[0];
            const type = document.getElementById('excelType').value;

            if (!file) {
                document.getElementById('excelResult').textContent = '请选择文件';
                return;
            }

            const formData = new FormData();
            formData.append('file', file);
            formData.append('type', type);

            try {
                const response = await fetch('/api/excel/upload', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();
                document.getElementById('excelResult').textContent = JSON.stringify(result, null, 2);
            } catch (error) {
                document.getElementById('excelResult').textContent = '错误: ' + error.message;
            }
        }

        async function downloadExcel() {
            const type = document.getElementById('excelType').value;
            window.open(`/api/excel/download?type=${type}`);
        }

        async function downloadTemplate() {
            const type = document.getElementById('excelType').value;
            window.open(`/api/excel/template?type=${type}`);
        }

        async function processExcelAsync() {
            const file = document.getElementById('excelFile').files[0];
            const type = document.getElementById('excelType').value;

            if (!file) {
                document.getElementById('excelResult').textContent = '请选择文件';
                return;
            }

            const formData = new FormData();
            formData.append('file', file);
            formData.append('type', type);

            try {
                const response = await fetch('/api/excel/batch', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();
                document.getElementById('excelResult').textContent = JSON.stringify(result, null, 2);
            } catch (error) {
                document.getElementById('excelResult').textContent = '错误: ' + error.message;
            }
        }

        async function exportExcel() {
            const type = document.getElementById('excelType').value;
            const resultDiv = document.getElementById('excelResult');
            
            try {
                // 清空之前的结果
                resultDiv.innerHTML = '';
                resultDiv.textContent = '正在创建导出任务...';
                
                // 发起导出请求
                const response = await fetch('/api/excel/export', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `type=${type}`
                });
                
                const result = await response.json();
                console.log('导出接口响应:', result);
                
                // 使用 result.code === 0 来判断成功
                if (result.code === 0) {
                    const taskId = result.data;
                    
                    // 保存任务信息到本地存储，用于优化取消操作
                    saveTaskInfoToStorage(taskId, {
                        model: 4, // 当前系统使用固定模块4（其他类型）
                        account: 'test', // 当前使用固定账户test
                        type: type
                    });
                    
                    resultDiv.innerHTML = `
                        <div style="color: #28a745; margin-bottom: 10px;">✅ 导出任务已创建</div>
                        <div><strong>任务ID:</strong> ${taskId}</div>
                        <div><strong>提示:</strong> ${result.msg || '导出任务已创建，请稍后查询任务状态'}</div>
                        <div id="task-status-${taskId}" style="margin-top: 15px; padding: 10px; background: #f8f9fa; border-radius: 5px;">
                            <div style="color: #007bff;">📊 正在查询任务状态...</div>
                        </div>
                        <div id="task-progress-${taskId}" style="margin-top: 10px;"></div>
                        <div id="task-download-${taskId}" style="margin-top: 15px;"></div>
                    `;
                    
                    // 开始轮询任务状态
                    pollTaskStatus(taskId);
                } else {
                    resultDiv.innerHTML = `
                        <div style="color: #dc3545; padding: 10px; background: #f8d7da; border-radius: 5px;">
                            <div>❌ 导出失败</div>
                            <div style="margin-top: 5px;">错误信息: ${result.msg}</div>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('导出请求失败:', error);
                resultDiv.innerHTML = `
                    <div style="color: #dc3545; padding: 10px; background: #f8d7da; border-radius: 5px;">
                        <div>❌ 请求失败</div>
                        <div style="margin-top: 5px;">错误: ${error.message}</div>
                        <div style="margin-top: 5px; font-size: 12px;">请检查网络连接和服务器状态</div>
                    </div>
                `;
            }
        }
        
        // 轮询任务状态
        async function pollTaskStatus(taskId) {
            const maxPolls = 30; // 最多轮询30次（约5分钟）
            let pollCount = 0;
            
            const statusDiv = document.getElementById(`task-status-${taskId}`);
            const progressDiv = document.getElementById(`task-progress-${taskId}`);
            const downloadDiv = document.getElementById(`task-download-${taskId}`);
            
            if (!statusDiv || !progressDiv || !downloadDiv) {
                console.error('找不到任务状态显示元素');
                return;
            }
            
            const poll = async () => {
                try {
                    pollCount++;
                    console.log(`第${pollCount}次轮询任务状态, 任务ID: ${taskId}`);
                    
                    const response = await fetch(`/api/excel/task/status/${taskId}`);
                    const result = await response.json();
                    console.log('任务状态响应:', result);
                    
                    // 使用 result.code === 0 来判断成功
                    if (result.code === 0 && result.data) {
                        const task = result.data;
                        const statusText = getStatusText(task.exportStatus);
                        const statusColor = getStatusColor(task.exportStatus);
                        
                        // 从任务响应中获取并更新本地存储的任务信息
                        if (task.model && task.zhangHu) {
                            const existingInfo = getTaskInfoFromStorage(taskId) || {};
                            saveTaskInfoToStorage(taskId, {
                                ...existingInfo,
                                model: task.model,
                                account: task.zhangHu,
                                fileName: task.fileName
                            });
                        }
                        
                        statusDiv.innerHTML = `
                            <div style="display: flex; align-items: center; margin-bottom: 10px;">
                                <span style="color: ${statusColor}; font-weight: bold;">状态: ${statusText}</span>
                                <span style="margin-left: 15px; color: #666;">${task.description || ''}</span>
                            </div>
                        `;
                        
                        // 显示进度条
                        if (task.progress !== undefined && task.progress !== null) {
                            const progressPercent = Number(task.progress) || 0;
                            progressDiv.innerHTML = `
                                <div style="margin-bottom: 10px;">
                                    <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                                        <span style="font-size: 12px; color: #666;">进度</span>
                                        <span style="font-size: 12px; color: #666;">${progressPercent}%</span>
                                    </div>
                                    <div style="background: #e9ecef; border-radius: 10px; overflow: hidden; height: 20px;">
                                        <div style="width: ${progressPercent}%; height: 100%; background: linear-gradient(90deg, #007bff, #0056b3); transition: width 0.3s ease;"></div>
                                    </div>
                                </div>
                            `;
                        }
                        
                        // 如果任务正在进行（队列中或导出中），显示取消按钮
                        if (task.exportStatus === 1 || task.exportStatus === 2) {
                            downloadDiv.innerHTML = `
                                <div style="padding: 15px; background: #e3f2fd; border: 1px solid #90caf9; border-radius: 5px;">
                                    <div style="color: #1565c0; font-weight: bold; margin-bottom: 10px;">
                                        ${task.exportStatus === 1 ? '📋 任务排队中...' : '⚙️ 正在处理中...'}
                                    </div>
                                    <div style="display: flex; gap: 10px; align-items: center;">
                                        <button onclick="cancelTaskWithConfirm('${taskId}')" 
                                                class="btn btn-outline-danger" 
                                                style="padding: 8px 16px; font-size: 12px; border-radius: 5px;">
                                            ❌ 取消任务
                                        </button>
                                        <span style="font-size: 12px; color: #666;">可以随时取消当前任务</span>
                                    </div>
                                    ${task.createDate ? `<div style="margin-top: 10px; font-size: 12px; color: #666;">⏰ 创建时间: ${task.createDate}</div>` : ''}
                                </div>
                            `;
                        }
                        
                        // 任务完成 - 提供下载链接
                        if (task.exportStatus === 3) {
                            downloadDiv.innerHTML = `
                                <div style="padding: 15px; background: #d4edda; border: 1px solid #c3e6cb; border-radius: 5px;">
                                    <div style="color: #155724; font-weight: bold; margin-bottom: 10px;">
                                        ✅ 导出完成！
                                    </div>
                                    <button onclick="downloadTaskFile('${taskId}')" 
                                            class="btn btn-success" 
                                            style="margin-top: 10px; padding: 10px 20px; font-size: 14px; border-radius: 5px; display: flex; align-items: center; justify-content: center; white-space: nowrap;">
                                        📥 下载文件
                                    </button>
                                    <div style="margin-top: 10px; font-size: 12px; color: #666;">
                                        📁 文件名: ${task.fileName || 'export.xlsx'}
                                        ${task.endDate ? `<br>⏰ 完成时间: ${task.endDate}` : ''}
                                        ${task.total ? `<br>📈 数据量: ${task.total} 条` : ''}
                                    </div>
                                </div>
                            `;
                            console.log('任务完成，停止轮询');
                            return; // 停止轮询
                        }
                        
                        // 任务失败
                        if (task.exportStatus === 4) {
                            downloadDiv.innerHTML = `
                                <div style="padding: 15px; background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 5px;">
                                    <div style="color: #721c24; font-weight: bold;">❌ 导出失败</div>
                                    <div style="font-size: 12px; color: #721c24; margin-top: 5px;">${task.description}</div>
                                    <button onclick="exportExcel()" 
                                            class="btn btn-secondary" 
                                            style="margin-top: 10px; padding: 8px 16px; font-size: 12px;">
                                        🔄 重新尝试
                                    </button>
                                </div>
                            `;
                            console.log('任务失败，停止轮询');
                            return; // 停止轮询
                        }
                        
                        // 任务取消
                        if (task.exportStatus === 5) {
                            downloadDiv.innerHTML = `
                                <div style="padding: 15px; background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 5px;">
                                    <div style="color: #856404; font-weight: bold;">⚠️ 任务已取消</div>
                                </div>
                            `;
                            console.log('任务取消，停止轮询');
                            return; // 停止轮询
                        }
                        
                        // 继续轮询（如果没有达到最大次数）
                        if (pollCount < maxPolls) {
                            setTimeout(poll, 2000); // 2秒后再次查询
                        } else {
                            statusDiv.innerHTML = `
                                <div style="padding: 10px; background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 5px;">
                                    <div style="color: #856404;">⚠️ 轮询超时，请手动刷新状态</div>
                                    <button onclick="pollTaskStatus('${taskId}')" 
                                            class="btn btn-warning" 
                                            style="margin-top: 10px; font-size: 12px; padding: 6px 12px;">
                                        🔄 刷新状态
                                    </button>
                                </div>
                            `;
                        }
                    } else {
                        // 查询失败，显示错误信息
                        statusDiv.innerHTML = `
                            <div style="padding: 10px; background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 5px;">
                                <div style="color: #721c24;">查询任务状态失败: ${result.msg}</div>
                                <button onclick="pollTaskStatus('${taskId}')" 
                                        class="btn btn-secondary" 
                                        style="margin-top: 10px; font-size: 12px; padding: 6px 12px;">
                                    🔄 重试
                                </button>
                            </div>
                        `;
                    }
                } catch (error) {
                    console.error('轮询请求失败:', error);
                    statusDiv.innerHTML = `
                        <div style="padding: 10px; background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 5px;">
                            <div style="color: #721c24;">网络错误: ${error.message}</div>
                            <button onclick="pollTaskStatus('${taskId}')" 
                                    class="btn btn-secondary" 
                                    style="margin-top: 10px; font-size: 12px; padding: 6px 12px;">
                                🔄 重试
                            </button>
                        </div>
                    `;
                }
            };
            
            // 立即执行第一次查询
            await poll();
        }
        
        // 获取状态文本
        function getStatusText(status) {
            const statusMap = {
                1: '队列中',
                2: '导出中', 
                3: '导出完成',
                4: '导出失败',
                5: '已取消'
            };
            return statusMap[status] || '未知状态';
        }
        
        // 获取状态颜色
        function getStatusColor(status) {
            const colorMap = {
                1: '#6c757d', // 灰色
                2: '#007bff', // 蓝色
                3: '#28a745', // 绿色
                4: '#dc3545', // 红色
                5: '#ffc107'  // 黄色
            };
            return colorMap[status] || '#6c757d';
        }
        
        // 下载任务文件
        async function downloadTaskFile(taskId) {
            const downloadDiv = document.getElementById(`task-download-${taskId}`);
            const originalContent = downloadDiv ? downloadDiv.innerHTML : '';
            
            try {
                console.log('开始下载文件，任务ID:', taskId);
                
                // 显示下载中状态
                if (downloadDiv) {
                    downloadDiv.innerHTML = `
                        <div style="padding: 15px; background: #cce5ff; border: 1px solid #99d6ff; border-radius: 5px;">
                            <div style="color: #0066cc; font-weight: bold; margin-bottom: 10px;">
                                📎 正在准备下载...
                            </div>
                            <div style="display: flex; align-items: center;">
                                <div class="spinner" style="width: 20px; height: 20px; margin-right: 10px;"></div>
                                <span style="color: #666; font-size: 12px;">请稍等，正在下载文件...</span>
                            </div>
                        </div>
                    `;
                }
                
                // 创建下载链接
                const downloadUrl = `/api/excel/file/download/${taskId}`;
                const link = document.createElement('a');
                link.href = downloadUrl;
                link.download = '';
                link.style.display = 'none';
                document.body.appendChild(link);
                
                // 触发下载
                link.click();
                
                // 清理DOM
                document.body.removeChild(link);
                
                // 显示成功状态
                if (downloadDiv) {
                    downloadDiv.innerHTML = `
                        <div style="padding: 15px; background: #d4edda; border: 1px solid #c3e6cb; border-radius: 5px;">
                            <div style="color: #155724; font-weight: bold; margin-bottom: 10px;">
                                ✅ 下载已开始！
                            </div>
                            <div style="color: #155724; font-size: 12px; margin-bottom: 10px;">
                                文件已开始下载，请检查浏览器下载目录。
                            </div>
                            <button onclick="downloadTaskFile('${taskId}')" 
                                    class="btn btn-success" 
                                    style="margin-right: 10px; padding: 8px 16px; font-size: 12px; display: flex; align-items: center; justify-content: center; white-space: nowrap;">
                                🔄 重新下载
                            </button>
                        </div>
                    `;
                }
                
                // 5秒后恢复原内容
                setTimeout(() => {
                    if (downloadDiv && originalContent) {
                        downloadDiv.innerHTML = originalContent;
                    }
                }, 5000);
                
                console.log('下载请求已发送');
                
            } catch (error) {
                console.error('下载失败:', error);
                
                // 显示错误状态
                if (downloadDiv) {
                    downloadDiv.innerHTML = `
                        <div style="padding: 15px; background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 5px;">
                            <div style="color: #721c24; font-weight: bold; margin-bottom: 10px;">
                                ❌ 下载失败
                            </div>
                            <div style="color: #721c24; font-size: 12px; margin-bottom: 10px;">
                                错误: ${error.message}
                            </div>
                            <button onclick="downloadTaskFile('${taskId}')" 
                                    class="btn btn-danger" 
                                    style="margin-right: 10px; padding: 8px 16px; font-size: 12px; display: flex; align-items: center; justify-content: center; white-space: nowrap;">
                                🔄 重试下载
                            </button>
                        </div>
                    `;
                }
                
                // 8秒后恢复原内容
                setTimeout(() => {
                    if (downloadDiv && originalContent) {
                        downloadDiv.innerHTML = originalContent;
                    }
                }, 8000);
            }
        }

        // 快速导出测试
        async function quickExportTest() {
            const resultDiv = document.getElementById('excelResult');
            
            try {
                resultDiv.innerHTML = `
                    <div style="padding: 15px; background: #e3f2fd; border: 1px solid #90caf9; border-radius: 5px;">
                        <div style="color: #1565c0; font-weight: bold; margin-bottom: 10px;">
                            🚀 快速测试模式
                        </div>
                        <div style="color: #1976d2; font-size: 12px;">
                            正在创建测试导出任务（使用EasyExcel库）...
                        </div>
                    </div>
                `;
                
                // 使用默认的EasyExcel库
                const response = await fetch('/api/excel/export', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'type=easyexcel'
                });
                
                const result = await response.json();
                console.log('快速测试响应:', result);
                
                if (result.code === 0) {
                    const taskId = result.data;
                    
                    // 保存任务信息到本地存储
                    saveTaskInfoToStorage(taskId, {
                        model: 4, // 快速测试使用模块4
                        account: 'test',
                        type: 'easyexcel'
                    });
                    
                    resultDiv.innerHTML = `
                        <div style="padding: 15px; background: #e8f5e8; border: 1px solid #81c784; border-radius: 5px;">
                            <div style="color: #2e7d32; font-weight: bold; margin-bottom: 10px;">
                                ✅ 快速测试任务已创建
                            </div>
                            <div style="color: #388e3c; margin-bottom: 10px;">
                                <strong>任务ID:</strong> ${taskId}
                            </div>
                            <div style="color: #4caf50; font-size: 12px; margin-bottom: 15px;">
                                📈 正在生成包含13条测试数据的Excel文件...
                            </div>
                        </div>
                        <div id="task-status-${taskId}" style="margin-top: 15px; padding: 10px; background: #f8f9fa; border-radius: 5px;">
                            <div style="color: #007bff;">📊 正在查询任务状态...</div>
                        </div>
                        <div id="task-progress-${taskId}" style="margin-top: 10px;"></div>
                        <div id="task-download-${taskId}" style="margin-top: 15px;"></div>
                    `;
                    
                    // 开始轮询任务状态
                    pollTaskStatus(taskId);
                } else {
                    resultDiv.innerHTML = `
                        <div style="padding: 15px; background: #ffebee; border: 1px solid #ef5350; border-radius: 5px;">
                            <div style="color: #c62828; font-weight: bold;">❌ 快速测试失败</div>
                            <div style="color: #d32f2f; margin-top: 5px;">错误信息: ${result.msg}</div>
                            <button onclick="quickExportTest()" 
                                    class="btn btn-danger" 
                                    style="margin-top: 10px; font-size: 12px; padding: 6px 12px;">
                                🔄 重试
                            </button>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('快速测试失败:', error);
                resultDiv.innerHTML = `
                    <div style="padding: 15px; background: #ffebee; border: 1px solid #ef5350; border-radius: 5px;">
                        <div style="color: #c62828; font-weight: bold;">❌ 网络请求失败</div>
                        <div style="color: #d32f2f; margin-top: 5px;">错误: ${error.message}</div>
                        <div style="color: #757575; font-size: 11px; margin-top: 8px;">
                            请检查：1. 服务器是否启动 2. 网络连接是否正常 3. Redis服务是否运行
                        </div>
                        <button onclick="quickExportTest()" 
                                class="btn btn-secondary" 
                                style="margin-top: 10px; font-size: 12px; padding: 6px 12px;">
                            🔄 重试
                        </button>
                    </div>
                `;
            }
        }

        async function getTaskList() {
            const account = document.getElementById('account').value;
            try {
                const response = await fetch(`/api/excel/task/list?account=${account}&model=4`);
                const result = await response.json();
                document.getElementById('taskResult').textContent = JSON.stringify(result, null, 2);
            } catch (error) {
                document.getElementById('taskResult').textContent = '错误: ' + error.message;
            }
        }

        async function getTaskStatus() {
            const taskId = document.getElementById('taskId').value;
            if (!taskId) {
                document.getElementById('taskResult').textContent = '请输入任务ID';
                return;
            }

            try {
                const response = await fetch(`/api/excel/task/status/${taskId}`);
                const result = await response.json();
                document.getElementById('taskResult').textContent = JSON.stringify(result, null, 2);
            } catch (error) {
                document.getElementById('taskResult').textContent = '错误: ' + error.message;
            }
        }

        // 带确认对话框的取消任务功能
        async function cancelTaskWithConfirm(taskId) {
            // 显示确认对话框
            const confirmed = confirm('确定要取消这个导出任务吗？\n\n取消后任务将停止执行，且无法恢复。');
            
            if (!confirmed) {
                return; // 用户取消操作
            }
            
            const downloadDiv = document.getElementById(`task-download-${taskId}`);
            const originalContent = downloadDiv ? downloadDiv.innerHTML : '';
            
            try {
                // 显示取消进度
                if (downloadDiv) {
                    downloadDiv.innerHTML = `
                        <div style="padding: 15px; background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 5px;">
                            <div style="color: #856404; font-weight: bold; margin-bottom: 10px;">
                                ⏳ 正在取消任务...
                            </div>
                            <div style="color: #856404; font-size: 12px;">
                                请稍候，正在停止任务执行并清理相关资源...
                            </div>
                        </div>
                    `;
                }
                
                console.log('发送取消请求，任务ID:', taskId);
                
                // 尝试获取任务的模块信息进行优化查找
                let cancelUrl = `/api/excel/task/cancel/${taskId}`;
                const taskInfo = getTaskInfoFromStorage(taskId);
                
                if (taskInfo && taskInfo.model) {
                    // 如果有模块信息，使用优化的取消接口
                    cancelUrl += `?model=${taskInfo.model}`;
                    console.log('使用优化取消模式，模块:', taskInfo.model);
                } else {
                    // 对于当前系统，默认使用模块4（其他类型）
                    cancelUrl += '?model=4';
                    console.log('使用默认模块4进行取消');
                }
                
                const response = await fetch(cancelUrl, {
                    method: 'POST'
                });
                
                const result = await response.json();
                console.log('取消请求响应:', result);
                
                if (result.code === 0) {
                    // 取消成功
                    if (downloadDiv) {
                        downloadDiv.innerHTML = `
                            <div style="padding: 15px; background: #d4edda; border: 1px solid #c3e6cb; border-radius: 5px;">
                                <div style="color: #155724; font-weight: bold; margin-bottom: 10px;">
                                    ✅ 任务已成功取消
                                </div>
                                <div style="color: #155724; font-size: 12px; margin-bottom: 10px;">
                                    ${result.msg || '任务已停止执行，相关资源已释放'}
                                </div>
                                <button onclick="exportExcel()" 
                                        class="btn btn-primary" 
                                        style="margin-top: 10px; padding: 8px 16px; font-size: 12px;">
                                    🚀 重新导出
                                </button>
                            </div>
                        `;
                    }
                    
                    // 更新状态显示
                    const statusDiv = document.getElementById(`task-status-${taskId}`);
                    if (statusDiv) {
                        statusDiv.innerHTML = `
                            <div style="display: flex; align-items: center; margin-bottom: 10px;">
                                <span style="color: #ffc107; font-weight: bold;">状态: 已取消</span>
                                <span style="margin-left: 15px; color: #666;">用户主动取消任务</span>
                            </div>
                        `;
                    }
                    
                    // 清空进度条
                    const progressDiv = document.getElementById(`task-progress-${taskId}`);
                    if (progressDiv) {
                        progressDiv.innerHTML = '';
                    }
                    
                    // 清理任务信息存储
                    removeTaskInfoFromStorage(taskId);
                    
                } else {
                    // 取消失败
                    if (downloadDiv) {
                        downloadDiv.innerHTML = `
                            <div style="padding: 15px; background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 5px;">
                                <div style="color: #721c24; font-weight: bold; margin-bottom: 10px;">
                                    ❌ 取消失败
                                </div>
                                <div style="color: #721c24; font-size: 12px; margin-bottom: 10px;">
                                    ${result.msg || '取消任务时发生错误'}
                                </div>
                                <div style="display: flex; gap: 10px;">
                                    <button onclick="cancelTaskWithConfirm('${taskId}')" 
                                            class="btn btn-outline-danger" 
                                            style="padding: 6px 12px; font-size: 12px;">
                                        🔄 重试取消
                                    </button>
                                    <button onclick="pollTaskStatus('${taskId}')" 
                                            class="btn btn-outline-secondary" 
                                            style="padding: 6px 12px; font-size: 12px;">
                                        🔄 刷新状态
                                    </button>
                                </div>
                            </div>
                        `;
                    }
                }
                
            } catch (error) {
                console.error('取消请求失败:', error);
                
                // 显示网络错误
                if (downloadDiv) {
                    downloadDiv.innerHTML = `
                        <div style="padding: 15px; background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 5px;">
                            <div style="color: #721c24; font-weight: bold; margin-bottom: 10px;">
                                🌐 网络请求失败
                            </div>
                            <div style="color: #721c24; font-size: 12px; margin-bottom: 10px;">
                                错误: ${error.message}
                            </div>
                            <div style="display: flex; gap: 10px;">
                                <button onclick="cancelTaskWithConfirm('${taskId}')" 
                                        class="btn btn-outline-danger" 
                                        style="padding: 6px 12px; font-size: 12px;">
                                    🔄 重试取消
                                </button>
                                <button onclick="pollTaskStatus('${taskId}')" 
                                        class="btn btn-outline-secondary" 
                                        style="padding: 6px 12px; font-size: 12px;">
                                    🔄 刷新状态
                                </button>
                            </div>
                        </div>
                    `;
                }
                
                // 5秒后恢复原内容
                setTimeout(() => {
                    if (downloadDiv && originalContent) {
                        downloadDiv.innerHTML = originalContent;
                    }
                }, 5000);
            }
        }

        // ===== 任务信息存储管理功能 =====
        
        /**
         * 存储任务信息到本地存储
         * @param {string} taskId 任务ID
         * @param {object} taskInfo 任务信息
         */
        function saveTaskInfoToStorage(taskId, taskInfo) {
            try {
                const taskData = {
                    taskId: taskId,
                    model: taskInfo.model || 4, // 默认模块4（其他类型）
                    account: taskInfo.account || 'test', // 默认账户
                    createTime: new Date().toISOString(),
                    type: taskInfo.type || 'easyexcel' // Excel库类型
                };
                
                localStorage.setItem(`task_${taskId}`, JSON.stringify(taskData));
                console.log('任务信息已存储:', taskData);
            } catch (error) {
                console.warn('存储任务信息失败:', error);
            }
        }
        
        /**
         * 从本地存储获取任务信息
         * @param {string} taskId 任务ID
         * @return {object|null} 任务信息或null
         */
        function getTaskInfoFromStorage(taskId) {
            try {
                const taskDataStr = localStorage.getItem(`task_${taskId}`);
                if (taskDataStr) {
                    const taskData = JSON.parse(taskDataStr);
                    console.log('获取到任务信息:', taskData);
                    return taskData;
                }
            } catch (error) {
                console.warn('获取任务信息失败:', error);
            }
            return null;
        }
        
        /**
         * 从本地存储删除任务信息
         * @param {string} taskId 任务ID
         */
        function removeTaskInfoFromStorage(taskId) {
            try {
                localStorage.removeItem(`task_${taskId}`);
                console.log('任务信息已删除:', taskId);
            } catch (error) {
                console.warn('删除任务信息失败:', error);
            }
        }
        
        /**
         * 清理过期的任务信息（超过24小时）
         */
        function cleanupExpiredTaskInfo() {
            try {
                const now = new Date();
                const keys = Object.keys(localStorage).filter(key => key.startsWith('task_'));
                
                keys.forEach(key => {
                    try {
                        const taskDataStr = localStorage.getItem(key);
                        if (taskDataStr) {
                            const taskData = JSON.parse(taskDataStr);
                            const createTime = new Date(taskData.createTime);
                            const hoursDiff = (now - createTime) / (1000 * 60 * 60);
                            
                            // 删除超过24小时的任务信息
                            if (hoursDiff > 24) {
                                localStorage.removeItem(key);
                                console.log('已清理过期任务信息:', key);
                            }
                        }
                    } catch (error) {
                        // 如果解析失败，直接删除
                        localStorage.removeItem(key);
                    }
                });
            } catch (error) {
                console.warn('清理过期任务信息失败:', error);
            }
        }

        async function cancelTask() {
            const taskId = document.getElementById('taskId').value;
            if (!taskId) {
                document.getElementById('taskResult').textContent = '请输入任务ID';
                return;
            }

            try {
                const response = await fetch(`/api/excel/task/cancel/${taskId}`, {
                    method: 'POST'
                });
                const result = await response.json();
                document.getElementById('taskResult').textContent = JSON.stringify(result, null, 2);
            } catch (error) {
                document.getElementById('taskResult').textContent = '错误: ' + error.message;
            }
        }

        async function convertGender() {
            const code = document.getElementById('genderCode').value;
            try {
                const response = await fetch('/api/enum/gender/convert', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `code=${code}`
                });
                const result = await response.json();
                document.getElementById('enumResult').textContent = JSON.stringify(result, null, 2);
            } catch (error) {
                document.getElementById('enumResult').textContent = '错误: ' + error.message;
            }
        }

        async function compressImage() {
            const file = document.getElementById('imageFile').files[0];
            if (!file) {
                document.getElementById('imageResult').textContent = '请选择图片文件';
                return;
            }

            const formData = new FormData();
            formData.append('file', file);
            formData.append('targetSizeKb', '100');

            try {
                const response = await fetch('/api/image/compress', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();
                document.getElementById('imageResult').textContent = JSON.stringify(result, null, 2);
            } catch (error) {
                document.getElementById('imageResult').textContent = '错误: ' + error.message;
            }
        }

        async function testEnhancedExcelExport() {
            const loading = document.getElementById('enhancedLoading');
            const result = document.getElementById('enhancedResult');

            try {
                loading.style.display = 'block';
                result.textContent = '正在生成Excel文件...';

                // 直接下载文件
                window.location.href = '/api/excel/enhanced/export';

                result.textContent = 'Excel文件生成成功！文件已开始下载。';
            } catch (error) {
                result.textContent = '错误: ' + error.message;
            } finally {
                loading.style.display = 'none';
            }
        }

        // ===== EasyExcel图片导入测试功能 =====
        
        // 处理EasyExcel文件选择
        function handleEasyExcelFileSelect(input) {
            const fileInfo = document.getElementById('easyExcelFileInfo');
            const fileName = document.getElementById('easyExcelFileName');
            const fileSize = document.getElementById('easyExcelFileSize');
            
            if (input.files && input.files[0]) {
                const file = input.files[0];
                
                // 显示文件信息
                fileName.textContent = file.name;
                fileSize.textContent = formatFileSize(file.size);
                fileInfo.style.display = 'block';
                
                console.log('EasyExcel文件已选择:', file.name, '大小:', file.size, 'bytes');
            } else {
                fileInfo.style.display = 'none';
            }
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // 下载EasyExcel测试模板
        async function downloadEasyExcelTemplate() {
            try {
                window.open('/api/image/template/download/easyexcel', '_blank');
                
                const result = document.getElementById('easyExcelResult');
                result.innerHTML = '✅ EasyExcel导入模板下载已开始，请检查浏览器下载目录。<br><br>模板说明：<br>• 包含姓名、年龄、图片1、图片2、备注字段<br>• 请在图片列中插入图片<br>• 支持.xlsx格式文件';
                result.style.display = 'block';
                
                // 3秒后隐藏提示
                setTimeout(() => {
                    result.style.display = 'none';
                }, 3000);
                
            } catch (error) {
                console.error('下载模板失败:', error);
                const result = document.getElementById('easyExcelResult');
                result.innerHTML = '❗ 下载模板失败：' + error.message;
                result.style.display = 'block';
            }
        }
        
        // 导入EasyExcel数据
        async function importEasyExcelData() {
            const fileInput = document.getElementById('easyExcelFile');
            const file = fileInput.files[0];
            
            if (!file) {
                alert('请先选择Excel文件');
                return;
            }
            
            const loading = document.getElementById('easyExcelLoading');
            const result = document.getElementById('easyExcelResult');
            const stats = document.getElementById('easyExcelStats');
            const dataPreview = document.getElementById('easyExcelDataPreview');
            
            // 重置显示状态
            result.style.display = 'none';
            stats.style.display = 'none';
            dataPreview.style.display = 'none';
            
            try {
                loading.style.display = 'block';
                
                const formData = new FormData();
                formData.append('file', file);
                
                console.log('开始上传EasyExcel文件:', file.name, '大小:', file.size, 'bytes');
                const startTime = Date.now();
                
                const response = await fetch('/api/image/extract/excel/easyexcel', {
                    method: 'POST',
                    body: formData
                });
                
                console.log('API响应状态:', response.status);
                const responseData = await response.json();
                console.log('API响应数据:', responseData);
                
                if (responseData.code === 0) {
                    const data = responseData.data;
                    const performanceStats = data.performanceStats || {};
                    
                    // 显示统计信息
                    const processTime = ((Date.now() - startTime) / 1000).toFixed(1);
                    document.getElementById('easyExcelDataCount').textContent = data.dataCount || 0;
                    document.getElementById('easyExcelImageCount').textContent = data.imageCount || 0;
                    document.getElementById('easyExcelProcessTime').textContent = processTime + 's';
                    stats.style.display = 'block';
                    
                    // 显示数据表格
                    displayEasyExcelDataTable(data.dataList || []);
                    
                    // 显示详细信息
                    result.innerHTML = `
                        <h4>✅ 导入成功</h4>
                        <p><strong>数据统计：</strong></p>
                        <ul>
                            <li>数据行数：${data.dataCount || 0} 条</li>
                            <li>图片数量：${data.imageCount || 0} 张</li>
                            <li>输出目录：${data.outputDir || 'N/A'}</li>
                        </ul>
                        <p><strong>性能统计：</strong></p>
                        <ul>
                            <li>总耗时：${performanceStats.totalTimeMs || 0} ms</li>
                            <li>工作簿创建：${performanceStats.workbookTimeMs || 0} ms</li>
                            <li>数据读取：${performanceStats.readTimeMs || 0} ms</li>
                        </ul>
                    `;
                    result.style.display = 'block';
                    
                } else {
                    const errorMsg = responseData.msg || '导入失败';
                    alert('导入失败: ' + errorMsg);
                    console.error('API返回失败状态:', responseData);
                    
                    result.innerHTML = `<h4>❌ 导入失败</h4><p>${errorMsg}</p>`;
                    result.style.display = 'block';
                }
                
            } catch (error) {
                console.error('导入EasyExcel数据失败:', error);
                alert('导入EasyExcel数据时发生错误: ' + error.message);
                
                result.innerHTML = `<h4>❌ 错误</h4><p>${error.message}</p>`;
                result.style.display = 'block';
            } finally {
                loading.style.display = 'none';
            }
        }
        
        // 显示EasyExcel数据表格
        function displayEasyExcelDataTable(dataList) {
            const dataPreview = document.getElementById('easyExcelDataPreview');
            const dataTableBody = document.getElementById('easyExcelDataTableBody');
            
            // 清空表格内容
            dataTableBody.innerHTML = '';
            
            if (!dataList || dataList.length === 0) {
                dataPreview.style.display = 'none';
                return;
            }
            
            // 填充表格数据
            dataList.forEach((item, index) => {
                const row = document.createElement('tr');
                row.style.backgroundColor = index % 2 === 0 ? '#f2f2f2' : 'white';
                row.innerHTML = `
                    <td style="border: 1px solid #ddd; padding: 8px;">${item.rowIndex || index + 1}</td>
                    <td style="border: 1px solid #ddd; padding: 8px;">${item.name || ''}</td>
                    <td style="border: 1px solid #ddd; padding: 8px;">${item.age || ''}</td>
                    <td style="border: 1px solid #ddd; padding: 8px;">
                        ${item.imagePath1 ? 
                            `<img src="/api/image/view?imagePath=${encodeURIComponent(item.imagePath1)}" 
                                  style="max-width: 80px; max-height: 50px; cursor: pointer; border-radius: 4px;" 
                                  alt="图片1" 
                                  onclick="showEasyExcelImageModal('${item.imagePath1}')">`
                            : '无图片'
                        }
                    </td>
                    <td style="border: 1px solid #ddd; padding: 8px;">
                        ${item.imagePath2 ? 
                            `<img src="/api/image/view?imagePath=${encodeURIComponent(item.imagePath2)}" 
                                  style="max-width: 80px; max-height: 50px; cursor: pointer; border-radius: 4px;" 
                                  alt="图片2" 
                                  onclick="showEasyExcelImageModal('${item.imagePath2}')">`
                            : '无图片'
                        }
                    </td>
                    <td style="border: 1px solid #ddd; padding: 8px;">${item.remark || ''}</td>
                `;
                dataTableBody.appendChild(row);
            });
            
            dataPreview.style.display = 'block';
        }
        
        // 显示EasyExcel图片模态框
        function showEasyExcelImageModal(imagePath) {
            if (!imagePath) return;
            
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.9);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 1000;
                cursor: pointer;
                opacity: 0;
                transition: opacity 0.3s ease;
            `;
            
            const modalContent = document.createElement('div');
            modalContent.style.cssText = `
                max-width: 90%;
                max-height: 90%;
                text-align: center;
                cursor: default;
            `;
            
            const img = document.createElement('img');
            img.src = `/api/image/view?imagePath=${encodeURIComponent(imagePath)}`;
            img.style.cssText = `
                max-width: 100%;
                max-height: 80vh;
                border-radius: 8px;
                box-shadow: 0 10px 30px rgba(0,0,0,0.5);
            `;
            
            const closeButton = document.createElement('div');
            closeButton.textContent = '✕';
            closeButton.style.cssText = `
                position: absolute;
                top: 20px;
                right: 30px;
                color: white;
                font-size: 24px;
                cursor: pointer;
                background: rgba(0,0,0,0.5);
                width: 40px;
                height: 40px;
                border-radius: 50%;
                display: flex;
                justify-content: center;
                align-items: center;
                transition: background 0.3s ease;
            `;
            
            closeButton.onmouseover = function() {
                this.style.background = 'rgba(255,255,255,0.2)';
            };
            
            closeButton.onmouseout = function() {
                this.style.background = 'rgba(0,0,0,0.5)';
            };
            
            modalContent.appendChild(img);
            modal.appendChild(modalContent);
            modal.appendChild(closeButton);
            document.body.appendChild(modal);
            
            // 淡入效果
            setTimeout(() => {
                modal.style.opacity = '1';
            }, 10);
            
            // 关闭事件
            const closeModal = function() {
                modal.style.opacity = '0';
                setTimeout(() => {
                    if (modal.parentNode) {
                        document.body.removeChild(modal);
                    }
                }, 300);
            };
            
            modal.onclick = closeModal;
            closeButton.onclick = closeModal;
            modalContent.onclick = function(e) {
                e.stopPropagation(); // 防止点击图片关闭模态框
            };
            
            // ESC键关闭
            const handleKeyDown = function(e) {
                if (e.key === 'Escape') {
                    closeModal();
                    document.removeEventListener('keydown', handleKeyDown);
                }
            };
            document.addEventListener('keydown', handleKeyDown);
        }
        
        // ===== 原有功能 =====

        
        // ===== 页面初始化 =====
        
        // 页面加载时的初始化操作
        window.addEventListener('DOMContentLoaded', function() {
            // 清理过期的任务信息
            cleanupExpiredTaskInfo();
            
            console.log('Excel Demo 页面已加载，已清理过期任务信息');
            
            // 显示优化提示
            console.log('🚀 取消功能已优化：支持精确查找，提升性能。');
        });
    </script>
</body>
</html>
